﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;

using Tszy.Unlimited.Base.Infrastructure.Caching.Redis;
using Tszy.Unlimited.Base.Infrastructure.Logging;

namespace Tszy.Unlimited.Base.Infrastructure.Caching;

/// <summary>
/// 缓存扩展。
/// </summary>
public static class CachingExtensions
{
    /// <summary>
    /// 注册缓存扩展。
    /// </summary>
    /// <param name="services"></param>
    /// <param name="cacheManager"></param>
    /// <returns></returns>
    public static IServiceCollection RegisterCache(this IServiceCollection services, ICacheManager cacheManager)
    {
        return services
            .RemoveAll(typeof(ICacheManager))
            .AddSingleton(cacheManager);
    }

    /// <summary>
    /// 注册 CSRedis 缓存扩展。
    /// </summary>
    /// <param name="services"></param>
    /// <param name="connectionString"></param>
    /// <returns></returns>
    public static IServiceCollection RegisterCacheCSRedis(this IServiceCollection services, string connectionString)
    {
        return services
            .RemoveAll(typeof(ICacheManager))
            .AddSingleton<ICacheManager>(sp => new CSRedisCacheManager(TszyLogger.Instance, connectionString));
    }

    /// <summary>
    /// 注册 CSRedis 缓存扩展。
    /// </summary>
    /// <param name="services"></param>
    /// <param name="host">主机地址。</param>
    /// <param name="port">端口号。</param>
    /// <param name="defaultDB">默认缓存库。</param>
    /// <param name="password">密码。</param>
    /// <param name="poolsize"></param>
    /// <returns></returns>
    public static IServiceCollection RegisterCacheCSRedis(this IServiceCollection services, string host, int port, int defaultDB, string password = "", int poolsize = 50)
    {
        return services
            .RemoveAll(typeof(ICacheManager))
            .AddSingleton<ICacheManager>(sp => new CSRedisCacheManager(TszyLogger.Instance, host, port, defaultDB, password, poolsize));
    }
}
